package com.car.servlet;

import com.car.service.UploadService;
import com.car.entyti.Upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    UploadService uploadService = new UploadService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part img = req.getPart("image");
        InputStream is = img.getInputStream();

        String fileName = img.getSubmittedFileName();

        String saveFileName = new Date().getTime() +
                fileName.substring(fileName.lastIndexOf("."));

        FileOutputStream fos = new FileOutputStream("D://" + saveFileName);

        byte[] ch = new byte[1024];
        int len = 0;
        while ((len = is.read(ch)) > 0) {
            fos.write(ch, 0, len);
        }

        fos.flush();
        fos.close();
        is.close();

        Upload upload = new Upload();
        upload.setImage("download?n=" + saveFileName);
        uploadService.Upimg(upload);
    }
}
